package com.lyf.service.user.Impl;

import com.lyf.context.BaseContext;
import com.lyf.mapper.user.AddressBookMapper;
import com.lyf.pojo.AddressBook;
import com.lyf.service.user.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;


    /**
     * 新增地址
     * @param addressBook
     */
    @Override
    public void save(AddressBook addressBook) {
        // 设置用户id
        addressBook.setUserId(BaseContext.getCurrentId());
        // 新的地址约定不为默认地址
        addressBook.setIsDefault(0);
        addressBookMapper.insert(addressBook);
    }

    @Override
    public void delete(Long id) {
        AddressBook addressBook = AddressBook.builder()
                .id(id)
                .build();
        addressBookMapper.delete(addressBook);
    }

    /**
     * 设置默认地址
     * @param addressBook
     */
    @Override
    public void setDefault(AddressBook addressBook) {
        // 设置为默认地址
        addressBook.setIsDefault(1);
        addressBookMapper.update(addressBook);
    }


    /**
     * 修改地址
     * @param addressBook
     */
    @Override
    public void update(AddressBook addressBook) {
        Long userId = BaseContext.getCurrentId();
        Long id = addressBook.getId();
        addressBookMapper.update(addressBook);
    }

    /**
     * 查询默认地址
     * @return
     */
    @Override
    public List<AddressBook> getDefault() {
        Long userId = BaseContext.getCurrentId();
        AddressBook addressBook = AddressBook.builder()
                .userId(userId)
                .isDefault(1)
                .build();
        List<AddressBook> list = addressBookMapper.list(addressBook);
        return list;
    }

    /**
     * 查询指定用户的所有地址
     * @return
     */
    @Override
    public List<AddressBook> list() {
        Long userId = BaseContext.getCurrentId();
        AddressBook addressBook = AddressBook.builder()
                .userId(userId)
                .build();
        List<AddressBook> list = addressBookMapper.list(addressBook);
        return list;
    }

    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    @Override
    public List<AddressBook> getById(Long id) {
        AddressBook addressBook = AddressBook.builder()
                .id(id)
                .build();
        List<AddressBook> list = addressBookMapper.list(addressBook);
        return list;
    }
}
